package org.tulkas.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:tulkas.web@gmail.com">Tulkas</a>
 *
 */
public abstract class SqlUtil {
	public static final String DEFAULT_DELIMITER = ";";
	private static final String LINE_SEPARATOR = System.getProperty(
			"line.separator", "\n");

	public static interface SqlHandler {
		public void handleSql(String sql);
	}

	public static String[] parseScript(String script) throws IOException {
		return parseScript(script, DEFAULT_DELIMITER);
	}

	public static String[] parseScript(String script, String delimiter)
			throws IOException {
		final List<String> list = new ArrayList<String>();
		SqlHandler handler = new SqlHandler() {
			@Override
			public void handleSql(String sql) {
				list.add(sql);
			}
		};
		StringReader reader = new StringReader(script);
		runScript(reader, handler, delimiter);
		return list.toArray(new String[list.size()]);
	}

	public static void runScript(Reader scriptReader, SqlHandler handler)
			throws IOException {
		runScript(scriptReader, handler, DEFAULT_DELIMITER);
	}

	public static void runScript(Reader scriptReader, SqlHandler handler,
			String delimiter) throws IOException {
		BufferedReader lineReader = new BufferedReader(scriptReader);
		String line;
		StringBuffer sql = new StringBuffer();
		while ((line = lineReader.readLine()) != null) {
			line = line.trim();
			if (line.startsWith("//") || line.startsWith("--")) {
			} else if (line.endsWith(delimiter)) {
				sql.append(line.substring(0, line.lastIndexOf(delimiter))
						.trim());
				if (sql.length() > 0) {
					handler.handleSql(sql.toString());
				}
				sql.setLength(0);
			} else if (line.length() > 0) {
				sql.append(line);
				sql.append(LINE_SEPARATOR);
			}
		}

		if (sql.length() > 0) {
			handler.handleSql(sql.toString());
		}
	}
}
